<!--
* description: 新增编辑-保养项目
* author:wangjuan
* createdDate:2020-12-4
-->
<template>
  <section class="editBigAreaInfo">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="false"
      :title="textMap[popupsState]"
      :append-to-body="true"
      :visible.sync="curPopupsVisible"
      width="70%"
      @close="closeEdit"
      @opened="open"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-params">
        <el-row ref="vailComponentList" :gutter="26">
          <one-table-template
            ref="multipleTable"
            :dynamic-components="tableComponents"
            :dynamic-api-config="apiConfig"
            :dynamic-form-fields="formField"
            :dynamic-is-show-select="true"
            :dynamic-is-show-more-btn="true"
          />
        </el-row>
      </div>

      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="工时信息" name="first">
            <one-table-template
              ref="multipleTable1"
              :dynamic-table-cols="tableCols"
              :dynamic-buttons="dynamicTableButtons"
              :dynamic-form-fields="formField1"
              :dynamic-is-show-select="false"
              :dynamic-is-show-more-btn="true"
              :dynamic-table-defult-height="300"
              :is-show-pagination="false"
            />
          </el-tab-pane>
          <el-tab-pane label="备件信息" name="second">
            <one-table-template
              ref="multipleTable2"
              :dynamic-table-cols="tableCols2"
              :dynamic-buttons="dynamicTableButtons2"
              :dynamic-form-fields="formField2"
              :dynamic-is-show-select="false"
              :dynamic-is-show-more-btn="true"
              :dynamic-table-defult-height="300"
              :is-show-pagination="false"
            >
              <!-- 备件信息 数量 -->
              <!-- <template #partQty="scope">
                <el-input
                  v-model="scope.row[scope.col.prop]"
                  placeholder="请输入"
                  type="number"
                  :min="1"
                  oninput="value=value.replace(/^[1-9]+$/,'')"
                />
              </template> -->
              <template #partQty="scope">
                <el-input-number
                  :key="'partQty' + scope.$index"
                  v-model="scope.row['partQty']"
                  :step="1"
                  :min="1"
                  :controls="false"
                  step-strictly
                />
              </template>
            </one-table-template>
          </el-tab-pane>
          <!-- 其他信息 -->
          <el-tab-pane label="其他信息" name="third">
            <one-table-template
              ref="multipleTable3"
              :dynamic-table-cols="tableCols3"
              :dynamic-buttons="dynamicTableButtons3"
              :dynamic-form-fields="formField3"
              :dynamic-is-show-select="false"
              :dynamic-is-show-more-btn="true"
              :dynamic-table-defult-height="300"
              :is-show-pagination="false"
            >
              <!-- 项目描述 -->
              <template #otherRemark="scope">
                <el-input
                  v-model="scope.row[scope.col.prop]"
                  placeholder="请输入"
                />
              </template>
              <!-- 总费用 -->
              <template #otherTotalFee="scope">
                <el-input
                  v-model="scope.row[scope.col.prop]"
                  placeholder="请输入"
                  type="number"
                  :min="0"
                  oninput="value=value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g,'').replace('.','$#$').replace(/\./g,'').replace('$#$','.').replace(/\.{2,}/g,'.').replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                />
              </template>
            </one-table-template>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
      <!-- 工时选择 -->
      <timeToChoose
        :key="editPopupsKey"
        :dynamic-edit-row-data="editRowData"
        :popups-visible-time="popupsVisibleTime"
        :popups-state="editPopupsState"
        :dynamic-api-style="'restful'"
        :chosen-list="chosenList"
        @close="close1"
        @returnTimeData="returnTimeData"
      />
      <!-- 备件选择 -->
      <sparePartsSelection
        :key="editPopupsKey2"
        :dynamic-edit-row-data="editRowData2"
        :popups-visible-part="popupsVisiblePart"
        :popups-state="editPopupsState2"
        :dynamic-api-style="'restful'"
        :chosen-p-list="chosenPList"
        @close="close2"
        @returnPartData="returnPartData"
      />
      <!-- 其他选择 -->
      <otherInformation
        :key="editPopupsKey3"
        :dynamic-edit-row-data="editRowData3"
        :popups-visible-other="popupsVisibleOther"
        :popups-state="editPopupsState3"
        :dynamic-api-style="'restful'"
        :chosen-o-list="chosenOList"
        @close="close3"
        @returnOtherData="returnOtherData"
      />
    </el-dialog>
  </section>
</template>
<script>
import Vue from 'vue'
import { formMixins } from '@/components/mixins/formMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { vehiclePdiPriceInquirys } from '@/api/se/vehiclePdiPriceInquiry'

export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader'),
    OneTableTemplate,
    timeToChoose: () => import('./timeToChoose'),
    sparePartsSelection: () => import('./sparePartsSelection'),
    otherInformation: () => import('./otherInformation')
  },

  // 组件混入对象
  mixins: [formMixins],

  props: {
    popupsVisible: { type: Boolean, default: false },
    // 从网格传入的编辑行数据(json)
    dynamicEditRowData: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },

  data() {
    const viewPageCode = 'bigAreaInfo-edit'
    return {
      apiConfig: vehiclePdiPriceInquirys.queryDlrParamSet,
      // 备件
      editPopupsKey: '1',
      editPopupsState: '',
      editRowData: {},
      chosenList: [],
      chosenPList: [],

      popupsVisiblePart: false,
      editRowData2: {},
      editPopupsKey2: '2',
      editPopupsState2: '',

      chosenOList: [],
      editRowData3: {},
      editPopupsKey3: '3',
      editPopupsState3: '',
      // 工时
      popupsVisibleTime: false,
      // 其他
      popupsVisibleOther: false,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save') /* 保存*/,
          position: 'right'
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          clickEvent: () => this.closeEdit(),
          text: this.$t('sys.button.cancel') // 取消
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '保养项目编码：',
              codeField: 'repairModeCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMust: true,
              disabled: true
            },
            // {
            //   compKey: 'compKey2',
            //   labelName: '车系：',
            //   codeField: 'isEnable',
            //   component: () => import('@/components/org/isEnable/isEnableOne'),
            //   type: 'dropdownList',
            //   isRequire: true,
            //   isMust: true
            // },
            {
              compKey: 'compKey3',
              labelName: '车型：',
              codeField: 'carTypeCode',
              oFields: 'carTypeCode,carTypeCn',
              component: () => import('@/components/org/commonSelect'),
              customObj: {
                api: {
                  APIUrl:
                      '/mp/e3sh/aftersale/maintenanceItemService/workRelaCarType.do'
                },
                selectType: '1'
              },
              type: 'dropdownList',
              isMust: true,
              isMul: true
            },
            {
              compKey: 'compKey4',
              labelName: '保养项目名称：',
              codeField: 'repairModeName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '保养项目描述：',
              codeField: 'repairModeContent',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMust: true
            },
            {
              compKey: 'compKey6',
              labelName: '状态：',
              codeField: 'isEnable',
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              oFields: 'statusId,statusText',
              options: [
                { statusId: '1', statusText: '启用' },
                { statusId: '0', statusText: '禁用' }
              ],
              isRequire: true,
              isMust: true
            }
          ],

      // 标题
      textMap: {
        edit: '保养项目编辑',
        add: '保养项目新增'
      },

      // 表单数据（无需赋值，由混入对象赋值）
      formField: this.$utils.getFormField(
        this,
        {
          repairModeCode: '',
          carTypeCode: '',
          repairModeName: '',
          repairModeContent: '',
          isEnableCn: '',
          isEnable: '',
          updateControlId: '',
          repairModeId: ''
        },
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode]
      ),

      activeName: 'first',

      // apiConfig1: api.queryExhibitionCarProductionByDetail,
      // 动态组件-按钮
      dynamicTableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.timeAddd(),
          text: '新增',
          isShow: true
        }
      ],

      tableCols: [
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlIdO',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlIdOd',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'transferOrderId',
          label: '展车主单id',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'transferOrderDId',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'controlBtn',
          label: '操作',
          codeField: 'controlBtn',
          width: 100,
          align: 'center',
          fixed: true,
          isComponent: true,
          comps: [
            {
              compKey: 'propKey1',
              align: 'center',
              labelName: '删除',
              clickEvent: (index) => this.handleDelete1(index),
              component: () => import('@/components/org/linkButton')
            }
          ]
        },
        {
          prop: 'wiCode',
          label: '工时编码',
          align: 'center'
        },
        {
          prop: 'repairContent',
          label: '维修内容',
          align: 'center'
        },
        {
          prop: 'saleWiQty',
          label: '标准工时',
          align: 'center'
        },
        {
          // prop: "opratePlaceName",
          prop: 'repariType',
          label: '工时大类',
          align: 'center'
        },
        {
          // prop: "rrpairSmallKindName",
          prop: 'rrpairSmallKindCode',
          label: '工时小类',
          align: 'center'
        }
      ],

      formField1: {
        wiCode: '', // 工时编码
        repairContent: '', // 维修内容
        saleWiQty: '', // 标准工时
        repariType: '', // 工时大类
        rrpairSmallKindCode: '' // 工时小类
      },

      tableCols2: [
        {
          prop: 'partRepairTypeCode',
          label: '备件类别code',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlIdO',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlIdOd',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'transferOrderId',
          label: '展车主单id',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'transferOrderDId',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'controlBtn',
          label: '操作',
          codeField: 'controlBtn',
          width: 100,
          align: 'center',
          fixed: true,
          isComponent: true,
          comps: [
            {
              compKey: 'propKey1',
              align: 'center',
              labelName: '删除',
              clickEvent: (index) => this.handleDelete2(index),
              component: () => import('@/components/org/linkButton')
            }
          ]
        },
        {
          prop: 'partNo',
          label: '备件编码',
          align: 'center'
        },
        {
          prop: 'partName',
          label: '备件名称',
          align: 'center'
        },
        {
          prop: 'partQty',
          label: '数量',
          align: 'center',
          isSlot: true
        },
        {
          prop: 'SNP',
          label: '包装含量',
          align: 'center'
        },
        {
          prop: 'partRepairType',
          label: '备件类别',
          align: 'center'
        }
        // {
        //   prop: "cityName",
        //   label: "适应车型",
        //   align: "center",
        // },
      ],
      tableCols3: [
        {
          prop: 'controlBtn',
          label: '操作',
          codeField: 'controlBtn',
          width: 100,
          align: 'center',
          fixed: true,
          isComponent: true,
          comps: [
            {
              compKey: 'propKey1',
              align: 'center',
              labelName: '删除',
              clickEvent: (index) => this.handleDelete3(index),
              component: () => import('@/components/org/linkButton')
            }
          ]
        },
        {
          prop: 'repairOtherCode',
          label: '其他项目编码',
          align: 'center'
        },
        {
          prop: 'repairOtherName',
          label: '其他项目名称',
          align: 'center'
        },
        {
          prop: 'otherRemark',
          label: '项目描述',
          align: 'center',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: true,
          isSlot: true
        },
        {
          prop: 'otherTotalFee',
          label: '总费用',
          align: 'center',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: true,
          isSlot: true
        },
        {
          prop: 'repairModeOtherId',
          label: '保养项目模板其他项目ID',
          align: 'center',
          hidden: true
        },
        {
          prop: 'repairModeId',
          label: '保养项目模板ID',
          align: 'center',
          hidden: true
        },
        {
          prop: 'repairOtherId',
          label: '其他项目ID',
          align: 'center',
          hidden: true
        },
        {
          prop: 'updateControlId',
          label: '并发控制字段',
          align: 'center',
          hidden: true
        }
      ],

      // 动态组件-按钮
      dynamicTableButtons2: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: (index) => this.partAdd(index),
          text: '新增',
          isShow: true
        }
      ],
      dynamicTableButtons3: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: (index) => this.otherAdd(index),
          text: '新增',
          isShow: true
        }
      ],

      formField2: {
        partNo: '', //  备件编
        partName: '', // 备件名称
        partQty: '0', //  数量
        SNP: '', //  包装含量
        businessType: '' // 备件类别
      },
      formField3: {
        repairModeOtherId: '', //  保养项目模板其他项目ID
        repairModeId: '', // 保养项目模板ID
        repairOtherId: '', //  其他项目ID
        repairOtherName: '', //  附加项目名称
        repairOtherCode: '', // 其他项目编码
        otherRemark: '', // 项目描述
        otherTotalFee: '', // 总金额
        updateControlId: '' // 并发控制字段
      }
    }
  },

  methods: {
    // partQtyChange(e) {
    //   let partQtyValue=e.toString();
    //   if (e < 1 || partQtyValue.indexOf(".")) {
    //     this.$message({
    //      message: "数量格式不正确",
    //      type: "success",
    //      duration: 1000,
    //    });
    //   }
    // },
    closeEdit() {
      this.curPopupsVisible = false
      this.popupsVisibleTime = false
      this.popupsVisiblePart = false
      this.popupsVisibleOther = false
      this.$emit('update:curPopupsVisible', false)
      this.$emit('close', false)
    },
    close3() {
      this.popupsVisibleOther = false
      this.queryTable(1)
    },
    close2() {
      this.popupsVisiblePart = false
      this.queryTable(1)
    },
    close1() {
      this.popupsVisibleTime = false
      this.editPopupsKey = this.$utils.generateId()
      this.queryTable(1)
    },

    handleClick(tab, event) {
      this.popupsVisibleTime = false
      this.popupsVisiblePart = false
      this.popupsVisibleOther = false
    },

    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpopup')
      if (this.valid) {
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: {
          APIUrl:
            '/mp/e3sh/aftersale/maintenanceItemService/updateSpareParts.do'
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          mapListResult: this.formField,
          spareParts: this.$refs.multipleTable2.list,
          workingHours: this.$refs.multipleTable1.list,
          other: this.$refs.multipleTable3.list
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 新增保存
    addSave() {
      if (!this.formField.isEnable) {
        this.$message({
          message: '状态不能为空',
          type: 'warn',
          duration: 1000
        })
        return
      }
      if (!this.formField.repairModeName) {
        this.$message({
          message: '保养项目名称不能为空',
          type: 'warn',
          duration: 1000
        })
        return
      }
      if (!this.formField.repairModeContent) {
        this.$message({
          message: '保养项目描述不能为空',
          type: 'warn',
          duration: 1000
        })
        return
      }
      // if (!this.formField.otherTotalFee) {
      //   this.$message({
      //     message: "总费用不能为空",
      //     type: "warn",
      //     duration: 1000,
      //   });
      //   return;
      // }
      const queryObj = {
        // 保存mutation
        type: 'mutation',
        // api配置
        apiConfig: {
          APIUrl:
            '/mp/e3sh/aftersale/maintenanceItemService/putMaintenanceItem.do'
        },
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          mapListResult: this.formField,
          spareParts: this.$refs.multipleTable2.list,
          workingHours: this.$refs.multipleTable1.list,
          other: this.$refs.multipleTable3.list
        }
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(queryObj)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            type: 'success',
            duration: 1000
          })
          this.curPopupsVisible = false
          this.$nextTick(() => {
            this.$parent.queryTable(1)
          })
        } else {
          // 保存失败
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },
    open() {
      if (this.popupsState == 'edit') {
        const queryObj = {
          // 保存mutation
          type: 'mutation',
          // api配置
          apiConfig: vehiclePdiPriceInquirys.queryEdit,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: { repairModeId: this.dynamicEditRowData.repairModeId }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        // 调用中台API方法（可复用）
        this.$requestAPI(paramD).then((response) => {
          // this.formField = response.rows.mapListResult;
          this.$refs.multipleTable1.list = response.rows.workingHours // 工时信息
          this.$refs.multipleTable2.list = response.rows.spareParts // 备件信息
          this.$refs.multipleTable3.list = response.rows.other // 其他信息
        })
      }
    },
    // 工时删除
    handleDelete1(index) {
      const that = this.$refs.multipleTable1
      that.list.forEach((element) => {
        if (element == that.list[index]) {
          that.list.splice(element, 1)
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    // 备件删除
    handleDelete2(index) {
      const that = this.$refs.multipleTable2
      that.list.forEach((element) => {
        if (element == that.list[index]) {
          that.list.splice(element, 1)
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },
    // 其他删除
    handleDelete3(index) {
      const that = this.$refs.multipleTable3
      that.list.forEach((element) => {
        if (element == that.list[index]) {
          that.list.splice(element, 1)
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000
          })
        }
      })
    },

    // 工时新增
    timeAddd() {
      this.editPopupsState = 'edit'
      this.chosenList = this.$refs['multipleTable1'].list.map(
        (o) => o['wiCode']
      )
      this.popupsVisibleTime = true
    },
    // 备件新增
    partAdd(index) {
      this.editPopupsState2 = 'edit'
      this.chosenPList = this.$refs['multipleTable2'].list.map(
        (o) => o['partNo']
      )
      this.popupsVisiblePart = true
      this.editRowData2 = this.$utils.deepCopy(
        this.$refs['multipleTable2'].list[index]
      )
    },
    // 其他新增
    otherAdd(index) {
      this.editPopupsState3 = 'edit'
      this.chosenOList = this.$refs['multipleTable3'].list.map(
        (o) => o['repairOtherId']
      )
      this.popupsVisibleOther = true
      this.editRowData3 = this.$utils.deepCopy(
        this.$refs['multipleTable3'].list[index]
      )
    },

    returnTimeData(returnData) {
      returnData.forEach((val) => {
        this.$refs.multipleTable1.list.push(val)
      })
    },

    returnPartData(returnData) {
      returnData.forEach((val) => {
        this.$refs.multipleTable2.list.push(val)
      })
    },

    returnOtherData(returnData) {
      returnData.forEach((val) => {
        this.$refs.multipleTable3.list.push(val)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.promptSpan {
  position: absolute;
  bottom: 26px;
  right: 335px;
  color: #e70020;
}
</style>

